<template>
    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" title="分配角色" width="30%" @close="handleClose">
        <el-form label-width="120px" ref="formRef" :model="form" :rules="rules">
            <el-form-item label="用户名">
                <el-input disabled :value="form.userName"></el-input>
            </el-form-item>

            <el-form-item label="角色列表">
                <el-checkbox-group v-model="form.userRoleIds">
                    <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
                        {{ role.roleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit()">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>

import { ref } from 'vue'
import { findAllRoles, findRoleByUserId } from '@/api/role'
import { doAssign } from '@/api/user'
import { ElMessage } from 'element-plus'
// 控制对话是否展示的变量
const dialogVisible = ref(false)
const formRef = ref()
const emit = defineEmits(['submit'])
const allRoles = ref<{
    id: string,
    roleName: string
}[]>([])
const form = ref({
    userId: null,
    userName: '',
    userRoleIds: [],
})
// 定义提交表单数据模型
const defaultForm = {
    userId: null,
    userName: '',
    userRoleIds: [],
}

const rules = ref({
    userRoleIds: [
        { required: true, message: '请选择角色', trigger: 'change' },
    ],

})


const handleClose = () => {
    form.value = defaultForm

}

//进入添加
const show = async (data: any) => {
    dialogVisible.value = true
    form.value.userId = data.id
    form.value.userName = data.name
    allRoles.value = (await findAllRoles()).data
    form.value.userRoleIds = (await findRoleByUserId(data.id)).data

}

const handleSubmit = () => {
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            doAssign(form.value).then(() => {
                ElMessage.success("分配成功")
                dialogVisible.value = false
                form.value = defaultForm
            })

        }
    })

}



defineExpose({
    show
})
</script>
<style scoped>
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>